<template>
  <t-dialog
    :width="width ? width : '80%'"
    :visible="showDialog"
    @confirm="handleConfirm"
    @close="handleCancel"
    @cancel="handleCancel"
    preventScrollThrough
    placement="center"
  >
    <template #header>{{ mode == "new" ? "新增" : mode == "edit" ? "编辑" : mode == "view" ? "查看" : "" }} </template>
    <t-form ref="formInstance" :data="pageData.formData" :rules="pageData.formRules">
      <t-space direction="vertical" style="width: 100%" size="large">
        <t-row v-if="mode === 'new'">
          <t-col :span="6">
            <t-form-item label="选择关联" :labelWidth="120">
              <t-button @click="handleFMRShow">{{
                pageData.fmrSelected ? "重选资方主体-国外主体的关联" : "选择资方主体-国外主体的关联"
              }}</t-button>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="6">
            <t-form-item label="资方主体" name="funderName" :labelWidth="120">
              <div class="form__text">{{ pageData.formData.funderName }}</div>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="国外主体" name="funderGlobalMainPartName" :labelWidth="120">
              <div class="form__text">{{ pageData.formData.funderGlobalMainPartName }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="6">
            <t-form-item label="截止日期" name="expiryDate" :labelWidth="120">
              <t-date-picker v-if="!pageData.readOnly" v-model="pageData.formData.expiryDate" style="width: 100%" />
              <div v-else class="form__text">
                {{ dayjs(pageData.formData.expiryDate).format("YYYY-MM-DD") }}
              </div>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="期限" name="dateLimit" :labelWidth="120">
              <t-select v-if="!pageData.readOnly" :disabled="mode !== 'new'" v-model="pageData.formData.dateLimit">
                <t-option label="60 日" :value="60" />
                <t-option label="90 日" :value="90" />
                <t-option label="120 日" :value="120" />
              </t-select>
              <div v-else class="form__text">{{ pageData.formData.dateLimit }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="6">
            <t-form-item label="金额单位" name="moneyUnit" :labelWidth="120">
              <t-select
                v-if="!pageData.readOnly"
                v-model="pageData.formData.moneyUnit"
                :options="CURRENCY_LIST"
                :disabled="mode !== 'new'"
              />
              <div v-else class="form__text">
                {{ getValueBySelectData(CURRENCY_LIST, pageData.formData.moneyUnit) }}
              </div>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="信用额度" name="creditLimit" :labelWidth="120">
              <t-input-number
                v-if="!pageData.readOnly"
                theme="column"
                :min="0"
                style="width: 100%"
                v-model="pageData.formData.creditLimit"
                :decimalPlaces="2"
              />
              <div v-else class="form__text">{{ newPrecision(pageData.formData.creditLimit, 2) }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row v-if="mode !== 'new'">
          <t-col :span="6">
            <t-form-item label="已用额度" name="creditUsed" :labelWidth="120">
              <div class="form__text">{{ newPrecision(pageData.formData.creditUsed, 2) }}</div>
            </t-form-item>
          </t-col>
        </t-row>
      </t-space>
    </t-form>
  </t-dialog>

  <SelectTable
    v-if="pageData.fmr.show"
    :loading="pageData.fmr.loading"
    :showDialog="pageData.fmr.show"
    title="选择资方-国外主体关联"
    width="60vw"
    tableMaxHeight="32vh"
    rowSelectionType="single"
    :tableData="pageData.fmr.data.records"
    :columns="fmrColumns"
    @onConfirm="handleFMRConfirm"
    @onCancel="handleFMRClose"
    :pagination="pageData.fmr.pagination"
    @page-change="handleFMRPageChange"
    :zIndex="2800"
  >
    <template #toolkit>
      <t-form class="crud-form" :data="pageData.fmr.filterValue">
        <t-space direction="vertical" style="width: 100%" size="small">
          <t-row>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="资方主体" name="funderName">
                <InputSelect :value="pageData.fmr.filterValue.funderName" @onClick="handleFunderShow" />
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="国外主体名称" name="funderGlobalMainPartName">
                <InputSelect :value="pageData.fmr.filterValue.funderGlobalMainPartName" @onClick="handleMainPartShow" />
              </t-form-item>
            </t-col>
          </t-row>
          <div class="crud-form__operations">
            <t-button theme="primary" @click="handleFMRFilterChange">查询</t-button>
            <t-button theme="warning" @click="handleFMRFilterReset">重置</t-button>
          </div>
        </t-space>
      </t-form>
    </template>
  </SelectTable>

  <SelectTable
    v-if="pageData.funder.show"
    :loading="pageData.funder.loading"
    title="选择资方"
    :showDialog="pageData.funder.show"
    width="60vw"
    rowSelectionType="single"
    :tableData="pageData.funder.data.records"
    :columns="funderColumns"
    @onConfirm="handleFunderConfirm"
    @onCancel="handleFunderClose"
    :pagination="pageData.funder.pagination"
    @page-change="handleFunderPageChange"
    :filter-value="pageData.funder.filterValue"
    @filter-change="handleFunderFilterChange"
    :zIndex="2810"
  />

  <SelectTable
    v-if="pageData.mainPart.show"
    :loading="pageData.mainPart.loading"
    title="选择国外主体"
    :showDialog="pageData.mainPart.show"
    width="60vw"
    rowSelectionType="single"
    tableMaxHeight="32vh"
    :tableData="pageData.mainPart.data.records"
    :columns="mainPartColumns"
    placement="center"
    @onConfirm="handleMainPartConfirm"
    @onCancel="handleMainPartClose"
    :pagination="pageData.mainPart.pagination"
    @page-change="handleMainPartPageChange"
    :zIndex="2820"
  >
    <template #toolkit>
      <t-form class="crud-form" :data="pageData.mainPart.filterValue">
        <t-space direction="vertical" style="width: 100%" size="small">
          <t-row>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="中文主体名称" name="customerName">
                <t-input
                  maxlength="50"
                  v-model="pageData.mainPart.filterValue.customerName"
                  placeholder="请输入中文主体名称进行筛选"
                />
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="英文主体名称" name="englishName">
                <t-input
                  maxlength="50"
                  v-model="pageData.mainPart.filterValue.englishName"
                  placeholder="请输入英文主体名称进行筛选"
                />
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="英文昵称" name="englishNickname">
                <t-input
                  maxlength="50"
                  v-model="pageData.mainPart.filterValue.englishNickname"
                  placeholder="请输入英文主体昵称进行筛选"
                />
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="所属地区" name="countryId">
                <InputSelect
                  :value="pageData.mainPart.filterValue.countryName"
                  placeholder="点击右边按钮选择国家/地区"
                  @onClick="handleRegionShow"
                />
              </t-form-item>
            </t-col>
          </t-row>

          <div class="crud-form__operations">
            <t-button theme="primary" @click="handleMainPartFilterChange">查询</t-button>
            <t-button theme="warning" @click="handleMainPartFilterReset">重置</t-button>
          </div>
        </t-space>
      </t-form>
    </template>
  </SelectTable>

  <SelectTable
    v-if="pageData.region.show"
    :loading="pageData.region.loading"
    title="选择国家/地区"
    :showDialog="pageData.region.show"
    width="60vw"
    rowSelectionType="single"
    :tableData="pageData.region.data.records"
    :columns="regionColumns"
    @onConfirm="handleRegionConfirm"
    @onCancel="handleRegionClose"
    :pagination="pageData.region.pagination"
    @page-change="handleRegionPageChange"
    :filter-value="pageData.region.filterValue"
    @filter-change="handleRegionFilterChange"
    :zIndex="2900"
  />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { MessagePlugin, type FormInstanceFunctions } from "tdesign-vue-next";
import { reactive, ref, toRaw } from "vue";

// TS 类型文件
import type { ISelectTableGroups } from "@/types";

// 工具函数
import dayjs from "dayjs";
import { getValueBySelectData, newPrecision } from "@/utils/tools";

// 常量
import { CURRENCY_LIST, PAGINATION_VALUE } from "@/common/constants";

// API
import { getFMRList, getFunderList, getMainPartList } from "@/api/merchants";
import { getRegionList } from "@/api/region";

// 业务数据
import { tableColumns as fmrColumns } from "@/pages/Dashboard/Merchants/FMR/components/columns";
import { tableColumns as funderColumns } from "@/pages/Dashboard/Merchants/Funder/components/columns";
import { tableColumns as mainPartColumns } from "@/pages/Dashboard/Merchants/MainPart/components/columns";
import { tableColumns as regionColumns } from "@/pages/Dashboard/Info/Region/components/columns";

const props = defineProps(["width", "showDialog", "mode", "editFormData"]);
const emits = defineEmits(["onCancel", "onConfirm"]);

const formInstance = ref<FormInstanceFunctions | null>(null);

const pageData = reactive({
  readOnly: false,
  fmrSelected: false,
  formData: {
    id: "",
    createdTime: "",
    createdBy: "",
    status: 0,
    remark: "",
    updatedBy: "",
    updatedTime: "",
    createdByName: "",
    updatedByName: "",
    hasDeleted: 0,
    fmrName: "",
    customerId: "",
    expiryDate: "",
    creditLimit: 0,
    moneyUnit: 0,
    creditUsed: 0,
    dateLimit: 0,
    funderId: "",
    funderName: "",
    funderGlobalMainPartId: "",
    funderGlobalMainPartName: "",
    funder: {
      id: "",
      createdTime: "",
      createdBy: "",
      status: 0,
      remark: "",
      updatedBy: "",
      updatedTime: "",
      createdByName: "",
      updatedByName: "",
      hasDeleted: 0,
      companyName: "",
      companyShortName: "",
      address: "",
      companyEngName: "",
      companyEngShortName: "",
      engAddress: "",
      bankName: "",
      bankEngName: "",
      bankEngAddress: "",
      swiftCode: "",
      bankAccount: "",
      payeeEngName: "",
      unionPayCode: ""
    },
    funderGlobalMainPart: {
      id: "",
      createdTime: "",
      createdBy: "",
      status: 0,
      remark: "",
      updatedBy: "",
      updatedTime: "",
      createdByName: "",
      updatedByName: "",
      hasDeleted: 0,
      customerName: "",
      englishName: "",
      englishNickname: "",
      countryId: "",
      country: ""
    }
  },
  formRules: {
    funderName: [{ required: true, message: "请选择资方主体", type: "error", trigger: "blur" }],
    dateLimit: [{ required: true, message: "请输入期限", type: "error", trigger: "blur" }],
    expiryDate: [{ required: true, message: "请输入有效时间", type: "error", trigger: "blur" }],
    moneyUnit: [{ required: true, message: "请输入货币单位", type: "error", trigger: "blur" }],
    creditLimit: [{ required: true, message: "请输入信用额度", type: "error", trigger: "blur" }]
  },
  fmr: {
    show: false,
    loading: false,
    data: {},
    filterValue: {
      funderId: "",
      funderName: "",
      funderGlobalMainPartId: "",
      funderGlobalMainPartName: ""
    },
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  } as ISelectTableGroups,
  funder: {
    show: false,
    loading: false,
    data: {},
    filterValue: {},
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  } as ISelectTableGroups,
  mainPart: {
    show: false,
    loading: false,
    data: {},
    filterValue: {
      customerName: "",
      englishName: "",
      englishNickname: "",
      countryId: "",
      countryName: ""
    },
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  } as ISelectTableGroups,
  region: {
    show: false,
    loading: false,
    data: {},
    filterValue: {
      countryName: ""
    },
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  } as ISelectTableGroups
});

const getFMRData = async () => {
  pageData.fmr.loading = true;
  const resultData = await getFMRList(
    pageData.fmr.pagination.current,
    pageData.fmr.pagination.pageSize,
    pageData.fmr.filterValue
  );
  if (resultData.code === 200) {
    pageData.fmr.data = resultData.data;
    pageData.fmr.pagination.total = resultData.data.total;
    pageData.fmr.pagination.current = resultData.data.current;
    pageData.fmr.pagination.pageSize = resultData.data.size;
    pageData.fmr.loading = false;
  }
};

const handleFMRShow = () => {
  pageData.fmr.show = true;
  pageData.fmr.filterValue = {};
  pageData.fmr.pagination = structuredClone(PAGINATION_VALUE);
  getFMRData();
};

const handleFMRConfirm = (e: Record<string, any>) => {
  // 标记选中状态，告诉用户已经选中了。
  pageData.fmrSelected = true;
  const { currentRowData } = e.options;

  // 国外主体信息名称、ID 导入到表单
  pageData.formData.funderGlobalMainPartId = currentRowData.funderGlobalMainPartId;
  pageData.formData.funderGlobalMainPartName = currentRowData.funderGlobalMainPart.customerName;

  // 资方信息名称、ID 导入到表单
  pageData.formData.funderId = currentRowData.funderId;
  pageData.formData.funderName = currentRowData.funder.companyName;
  handleFMRClose();
};

const handleFMRClose = () => {
  pageData.fmr.show = false;
};

const handleFMRFilterChange = () => {
  pageData.fmr.pagination = structuredClone(PAGINATION_VALUE);
  getFMRData();
};

const handleFMRFilterReset = () => {
  pageData.fmr.pagination = structuredClone(PAGINATION_VALUE);
  pageData.fmr.filterValue = { funderId: "", funderName: "", funderGlobalMainPartId: "", funderGlobalMainPartName: "" };
  getFMRData();
};

const handleFMRPageChange = (pageInfo: Record<string, any>) => {
  pageData.fmr.pagination.pageSize = pageInfo.pageSize;
  pageData.fmr.pagination.current = pageInfo.current;
  getFMRData();
};

// 资方的选择列表方法
const getFunderData = async () => {
  pageData.funder.loading = true;
  const resultData = await getFunderList(
    pageData.funder.pagination.current,
    pageData.funder.pagination.pageSize,
    pageData.funder.filterValue
  );
  if (resultData.code === 200) {
    pageData.funder.data = resultData.data;
    pageData.funder.pagination.total = resultData.data.total;
    pageData.funder.pagination.current = resultData.data.current;
    pageData.funder.pagination.pageSize = resultData.data.size;
    pageData.funder.loading = false;
  }
};

const handleFunderConfirm = (e: Record<string, any>) => {
  pageData.fmr.filterValue.funderId = e.options.currentRowData.id;
  pageData.fmr.filterValue.funderName = e.options.currentRowData.companyName;
  handleFunderClose();
};

const handleFunderShow = () => {
  pageData.funder.show = true;
  getFunderData();
};
const handleFunderClose = () => {
  pageData.funder.show = false;
};

const handleFunderFilterChange = (filters: Record<string, any>) => {
  pageData.funder.filterValue = filters;
  pageData.funder.pagination = structuredClone(PAGINATION_VALUE);
  getFunderData();
};

const handleFunderPageChange = (pageInfo: Record<string, any>) => {
  pageData.funder.pagination.pageSize = pageInfo.pageSize;
  pageData.funder.pagination.current = pageInfo.current;
  getFunderData();
};

// 国外主体的的选择列表方法
const getMainPartData = async () => {
  pageData.funder.loading = true;
  const resultData = await getMainPartList(
    pageData.mainPart.pagination.current,
    pageData.mainPart.pagination.pageSize,
    pageData.mainPart.filterValue
  );
  if (resultData.code === 200) {
    pageData.mainPart.data = resultData.data;
    pageData.mainPart.pagination.total = resultData.data.total;
    pageData.mainPart.pagination.current = resultData.data.current;
    pageData.mainPart.pagination.pageSize = resultData.data.size;
    pageData.mainPart.loading = false;
  }
};

const handleMainPartConfirm = (e: Record<string, any>) => {
  pageData.fmr.filterValue.funderGlobalMainPartId = e.options.currentRowData.id;
  pageData.fmr.filterValue.funderGlobalMainPartName = e.options.currentRowData.customerName;
  handleMainPartClose();
};

const handleMainPartShow = () => {
  pageData.mainPart.show = true;
  getMainPartData();
};
const handleMainPartClose = () => {
  pageData.mainPart.show = false;
};

const handleMainPartFilterChange = () => {
  pageData.mainPart.pagination = structuredClone(PAGINATION_VALUE);
  getMainPartData();
};

const handleMainPartFilterReset = () => {
  pageData.mainPart.pagination = structuredClone(PAGINATION_VALUE);
  pageData.mainPart.filterValue = {
    customerName: "",
    englishName: "",
    englishNickname: "",
    countryId: "",
    countryName: ""
  };
  getMainPartData();
};

const handleMainPartPageChange = (pageInfo: Record<string, any>) => {
  pageData.mainPart.pagination.pageSize = pageInfo.pageSize;
  pageData.mainPart.pagination.current = pageInfo.current;
  getMainPartData();
};

// 国家地区列表选择方法
const getRegionData = async () => {
  pageData.region.loading = true;
  const resultData = await getRegionList(
    pageData.region.pagination.current,
    pageData.region.pagination.pageSize,
    pageData.region.filterValue
  );
  if (resultData.code === 200) {
    pageData.region.data = resultData.data;
    pageData.region.pagination.total = resultData.data.total;
    pageData.region.pagination.current = resultData.data.current;
    pageData.region.pagination.pageSize = resultData.data.size;
    pageData.region.loading = false;
  }
};

const handleRegionConfirm = (e: Record<string, any>) => {
  pageData.mainPart.filterValue.countryId = e.options.currentRowData.id;
  pageData.mainPart.filterValue.countryName = e.options.currentRowData.countryName;
  handleRegionClose();
};

const handleRegionShow = () => {
  pageData.region.show = true;
  getRegionData();
};
const handleRegionClose = () => {
  pageData.region.show = false;
};

const handleRegionFilterChange = (filters: Record<string, any>) => {
  pageData.region.filterValue = filters;
  pageData.region.pagination = structuredClone(PAGINATION_VALUE);
  getRegionData();
};

const handleRegionPageChange = (pageInfo: Record<string, any>) => {
  // console.log(pageInfo, newDataSource);
  pageData.region.pagination.pageSize = pageInfo.pageSize;
  pageData.region.pagination.current = pageInfo.current;
  getRegionData();
};

const handleCancel = () => {
  emits("onCancel");
};

const handleConfirm = async () => {
  const validateResult = await formInstance.value?.validate();
  if (validateResult !== true) {
    return;
  }
  if (props.mode === "new" && !pageData.fmrSelected) {
    MessagePlugin.error("请先选择资方主体-国外主体信息关联！");
    return;
  }
  emits("onConfirm", toRaw(pageData.formData));
};

if (props.editFormData) {
  pageData.formData = toRaw(props.editFormData);
}
</script>
